package mynet

import (
	"encoding/binary"
	"net"
	"time"
)

type Client struct {
	addr string
}

func (c Client) Send(msg string) (string, error) {
	conn, err := net.DialTimeout("tcp", c.addr, 3*time.Second)
	if err != nil {
		return "", err
	}
	defer func() {
		_ = conn.Close()
	}()
	//总长度
	bs := make([]byte, lenthByte, len(msg)+lenthByte)
	//写入消息长度
	binary.BigEndian.PutUint64(bs, uint64(len(msg)))
	bs = append(bs, msg...)
	_, err = conn.Write(bs)
	if err != nil {
		return "", err
	}
	//读取响应长度
	lenBs := make([]byte, lenthByte)
	_, err = conn.Read(lenBs)
	if err != nil {
		return "", err
	}
	resLength := binary.BigEndian.Uint64(lenBs)
	//读取响应
	resBs := make([]byte, resLength)
	_, err = conn.Read(resBs)
	if err != nil {
		return "", err
	}
	return string(resBs), nil
}
